<template>
  <div class="promotion-detail">
    <!-- 基本信息卡片 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>活动基本信息</span>
          <el-button-group>
            <el-button type="primary" @click="handleEdit">编辑</el-button>
            <el-button type="danger" @click="handleDelete" :disabled="promotion.status === 'running'">
              删除
            </el-button>
          </el-button-group>
        </div>
      </template>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="活动名称">{{ promotion.name }}</el-descriptions-item>
        <el-descriptions-item label="活动类型">
          <el-tag :type="getPromotionTypeTag(promotion.type)">
            {{ getPromotionTypeName(promotion.type) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="活动状态">
          <el-tag :type="getPromotionStatusTag(promotion.status)">
            {{ getPromotionStatusName(promotion.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ promotion.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ promotion.endTime }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ promotion.createTime }}</el-descriptions-item>
        <el-descriptions-item label="活动规则" :span="3">{{ promotion.rules }}</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 数据统计卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>参与人数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.participants }}</div>
            <div class="trend">
              较昨日
              <span :class="statistics.participantsTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.participantsTrend) }}%
                <el-icon>
                  <component :is="statistics.participantsTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>转化率</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.conversionRate }}%</div>
            <div class="trend">
              较昨日
              <span :class="statistics.conversionTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.conversionTrend) }}%
                <el-icon>
                  <component :is="statistics.conversionTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>销售额</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">¥{{ statistics.sales }}</div>
            <div class="trend">
              较昨日
              <span :class="statistics.salesTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.salesTrend) }}%
                <el-icon>
                  <component :is="statistics.salesTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover">
          <template #header>
            <div class="card-header">
              <span>订单数</span>
            </div>
          </template>
          <div class="card-content">
            <div class="amount">{{ statistics.orders }}</div>
            <div class="trend">
              较昨日
              <span :class="statistics.ordersTrend >= 0 ? 'up' : 'down'">
                {{ Math.abs(statistics.ordersTrend) }}%
                <el-icon>
                  <component :is="statistics.ordersTrend >= 0 ? 'ArrowUp' : 'ArrowDown'" />
                </el-icon>
              </span>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据趋势图表 -->
    <el-card class="chart-card">
      <template #header>
        <div class="card-header">
          <span>数据趋势</span>
          <el-radio-group v-model="chartType" size="small">
            <el-radio-button label="participants">参与人数</el-radio-button>
            <el-radio-button label="conversion">转化率</el-radio-button>
            <el-radio-button label="sales">销售额</el-radio-button>
            <el-radio-button label="orders">订单数</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      <div class="chart-container">
        <v-chart :option="chartOption" autoresize />
      </div>
    </el-card>

    <!-- 活动商品列表 -->
    <el-card class="product-card">
      <template #header>
        <div class="card-header">
          <span>活动商品</span>
        </div>
      </template>
      <el-table :data="productList" border style="width: 100%">
        <el-table-column prop="name" label="商品名称" min-width="200" />
        <el-table-column prop="price" label="原价" width="120">
          <template #default="{ row }">
            ¥{{ row.price }}
          </template>
        </el-table-column>
        <el-table-column prop="promotionPrice" label="活动价" width="120">
          <template #default="{ row }">
            ¥{{ row.promotionPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" />
        <el-table-column prop="sales" label="销量" width="100" />
        <el-table-column prop="conversionRate" label="转化率" width="100">
          <template #default="{ row }">
            {{ row.conversionRate }}%
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewProduct(row)">
              查看
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 参与记录列表 -->
    <el-card class="record-card">
      <template #header>
        <div class="card-header">
          <span>参与记录</span>
          <el-button type="primary" @click="handleExport">导出记录</el-button>
        </div>
      </template>
      <el-table :data="recordList" border style="width: 100%">
        <el-table-column prop="memberName" label="会员名称" min-width="120" />
        <el-table-column prop="memberLevel" label="会员等级" width="120">
          <template #default="{ row }">
            <el-tag>{{ row.memberLevel }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="joinTime" label="参与时间" width="180" />
        <el-table-column prop="orderAmount" label="订单金额" width="120">
          <template #default="{ row }">
            ¥{{ row.orderAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getOrderStatusTag(row.status)">
              {{ getOrderStatusName(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleViewOrder(row)">
              查看订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="recordPage.current"
          v-model:page-size="recordPage.size"
          :total="recordPage.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRecordSizeChange"
          @current-change="handleRecordCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowUp, ArrowDown } from '@element-plus/icons-vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart } from 'echarts/charts'
import { GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import VChart from 'vue-echarts'
import {
  getMerchantPromotionDetail,
  deleteMerchantPromotion,
  getMerchantPromotionStatistics,
  getMerchantPromotionTrend,
  getMerchantPromotionProducts,
  getMerchantPromotionRecords,
  exportMerchantPromotionData
} from '@/api/merchant'

// 注册 ECharts 组件
use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent])

const route = useRoute()
const router = useRouter()
const promotionId = route.params.id

// 活动信息
const promotion = ref({})

// 统计数据
const statistics = reactive({
  participants: 0,
  participantsTrend: 0,
  conversionRate: 0,
  conversionTrend: 0,
  sales: 0,
  salesTrend: 0,
  orders: 0,
  ordersTrend: 0
})

// 图表数据
const chartType = ref('participants')
const chartData = ref({
  dates: [],
  participants: [],
  conversion: [],
  sales: [],
  orders: []
})

// 商品列表
const productList = ref([])

// 参与记录
const recordList = ref([])
const recordPage = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取活动详情
const getPromotionDetail = async () => {
  try {
    const { data } = await getMerchantPromotionDetail(promotionId)
    promotion.value = data
  } catch (error) {
    console.error('获取活动详情失败:', error)
    ElMessage.error('获取活动详情失败')
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const { data } = await getMerchantPromotionStatistics(promotionId)
    Object.assign(statistics, data)
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败')
  }
}

// 获取趋势数据
const getTrendData = async () => {
  try {
    const { data } = await getMerchantPromotionTrend(promotionId)
    chartData.value = data
  } catch (error) {
    console.error('获取趋势数据失败:', error)
    ElMessage.error('获取趋势数据失败')
  }
}

// 获取商品列表
const getProductList = async () => {
  try {
    const { data } = await getMerchantPromotionProducts(promotionId)
    productList.value = data
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.error('获取商品列表失败')
  }
}

// 获取参与记录
const getRecordList = async () => {
  try {
    const params = {
      page: recordPage.current,
      size: recordPage.size
    }
    const { data } = await getMerchantPromotionRecords(promotionId, params)
    recordList.value = data.list
    recordPage.total = data.total
  } catch (error) {
    console.error('获取参与记录失败:', error)
    ElMessage.error('获取参与记录失败')
  }
}

// 图表配置
const chartOption = computed(() => ({
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: [getChartTitle(chartType.value)]
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: chartData.value.dates
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: getChartTitle(chartType.value),
      type: 'line',
      smooth: true,
      data: chartData.value[chartType.value]
    }
  ]
}))

// 获取图表标题
const getChartTitle = (type) => {
  const map = {
    participants: '参与人数',
    conversion: '转化率',
    sales: '销售额',
    orders: '订单数'
  }
  return map[type] || ''
}

// 活动类型标签
const getPromotionTypeTag = (type) => {
  const map = {
    discount: 'success',
    seckill: 'danger',
    group: 'warning',
    new_user: 'info'
  }
  return map[type] || ''
}

// 活动类型名称
const getPromotionTypeName = (type) => {
  const map = {
    discount: '满减活动',
    seckill: '秒杀活动',
    group: '拼团活动',
    new_user: '新人专享'
  }
  return map[type] || type
}

// 活动状态标签
const getPromotionStatusTag = (status) => {
  const map = {
    draft: 'info',
    pending: 'warning',
    running: 'success',
    ended: ''
  }
  return map[status] || ''
}

// 活动状态名称
const getPromotionStatusName = (status) => {
  const map = {
    draft: '草稿',
    pending: '待开始',
    running: '进行中',
    ended: '已结束'
  }
  return map[status] || status
}

// 订单状态标签
const getOrderStatusTag = (status) => {
  const map = {
    pending: 'warning',
    paid: 'success',
    completed: 'info',
    cancelled: 'danger'
  }
  return map[status] || ''
}

// 订单状态名称
const getOrderStatusName = (status) => {
  const map = {
    pending: '待付款',
    paid: '已付款',
    completed: '已完成',
    cancelled: '已取消'
  }
  return map[status] || status
}

// 编辑活动
const handleEdit = () => {
  router.push(`/merchant/marketing/edit/${promotionId}`)
}

// 删除活动
const handleDelete = async () => {
  if (promotion.value.status === 'running') {
    ElMessage.warning('进行中的活动无法删除')
    return
  }
  try {
    await ElMessageBox.confirm('确认删除该活动吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantPromotion(promotionId)
    ElMessage.success('删除成功')
    router.push('/merchant/marketing')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
    }
  }
}

// 查看商品
const handleViewProduct = (row) => {
  router.push(`/merchant/product/detail/${row.id}`)
}

// 查看订单
const handleViewOrder = (row) => {
  router.push(`/merchant/order/detail/${row.orderId}`)
}

// 导出记录
const handleExport = async () => {
  try {
    const params = {
      promotionId,
      type: 'record'
    }
    await exportMerchantPromotionData(params)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出记录失败:', error)
    ElMessage.error('导出记录失败')
  }
}

// 分页
const handleRecordSizeChange = (val) => {
  recordPage.size = val
  getRecordList()
}

const handleRecordCurrentChange = (val) => {
  recordPage.current = val
  getRecordList()
}

onMounted(() => {
  getPromotionDetail()
  getStatistics()
  getTrendData()
  getProductList()
  getRecordList()
})
</script>

<style lang="scss" scoped>
.promotion-detail {
  padding: 20px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .info-card {
    margin-bottom: 20px;
  }

  .statistics-cards {
    margin-bottom: 20px;

    .card-content {
      text-align: center;

      .amount {
        font-size: 24px;
        font-weight: bold;
        margin-bottom: 10px;
      }

      .trend {
        font-size: 14px;
        color: var(--el-text-color-secondary);

        .up {
          color: var(--el-color-success);
        }

        .down {
          color: var(--el-color-danger);
        }
      }
    }
  }

  .chart-card {
    margin-bottom: 20px;

    .chart-container {
      height: 400px;
    }
  }

  .product-card,
  .record-card {
    margin-bottom: 20px;
  }

  .pagination {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 